<template>
  <div class="game-container">
    <!-- 顶部状态栏 -->
    <div class="status-section">
      <el-card class="player-card" :body-style="{ padding: '0px' }">
        <div class="player-info">
          <div class="player-avatar">
            <el-avatar :size="80" :src="playerInfo.avatar" />
            <div class="player-address">{{ formatAddress(walletStore.walletAddress) }}</div>
          </div>
          <div class="energy-info">
            <div class="energy-title">
              <el-icon><Star /></el-icon>
              <span>探索能量</span>
              <el-button 
                type="primary" 
                link 
                @click="addEnergy"
                class="add-energy-btn"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
            <el-progress 
              :percentage="(playerInfo.energy / 100) * 100" 
              :format="format => playerInfo.energy + '/100'"
              :status="playerInfo.energy >= 10 ? 'success' : 'exception'"
              :stroke-width="20"
              class="energy-bar"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 主游戏区域 -->
    <div class="main-section">
      <!-- 探索区域 -->
      <div class="explore-section">
        <div class="explore-background"></div>
        <div class="explore-content">
          <div class="explore-title">
            <h1>数字宝藏探索</h1>
            <p>每次探索消耗 10 点能量，挖掘到宝箱后需要解答问题才能获得 NFT！</p>
          </div>
          <div class="explore-action">
            <el-button 
              type="primary" 
              :disabled="!canExplore || isExploring"
              @click="startExploration"
              size="large"
              class="explore-button"
            >
              <template #icon>
                <el-icon><Search /></el-icon>
              </template>
              {{ isExploring ? '探索中...' : '开始探索' }}
            </el-button>
            <div class="energy-cost" v-if="playerInfo.energy < 10">
              能量不足，需要等待恢复
            </div>
          </div>
        </div>
      </div>

      <!-- 探索日志 -->
      <div class="log-section">
        <el-card class="log-card">
          <template #header>
            <div class="log-header">
              <h3>探索日志</h3>
              <el-button type="primary" link @click="clearLog">清空</el-button>
            </div>
          </template>
          <div class="log-content" ref="logContent">
            <div 
              v-for="(log, index) in explorationLogs" 
              :key="index"
              class="log-item"
              :class="'log-' + log.type"
            >
              <span class="log-time">{{ formatTime(log.time) }}</span>
              <span class="log-text">{{ log.message }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 发现宝箱弹窗 -->
    <el-dialog
      v-model="treasureDialog.visible"
      title="发现神秘宝箱！"
      width="500px"
      center
      :show-close="false"
      class="treasure-dialog"
    >
      <div class="treasure-result">
        <div class="treasure-animation">
          <img src="https://cdn-icons-png.flaticon.com/512/2535/2535557.png" alt="宝箱" class="treasure-image1">
        </div>
        <div class="treasure-info">
          <h3>你发现了一个神秘的宝箱！</h3>
          <p>解答问题即可打开宝箱，获得稀有NFT！</p>
          <div class="treasure-question" v-if="treasureDialog.question">
            <div class="question-text">{{ treasureDialog.question }}</div>
            <el-input
              v-model="treasureDialog.answer"
              placeholder="输入你的答案"
              class="answer-input"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="skipTreasure">稍后解锁</el-button>
          <el-button 
            type="primary" 
            @click="unlockTreasure"
            :loading="treasureDialog.unlocking"
          >
            解锁宝箱
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 解锁结果弹窗 -->
    <el-dialog
      v-model="unlockResult.visible"
      :title="unlockResult.success ? '解锁成功！' : '解锁失败'"
      width="500px"
      center
      destroy-on-close
      class="result-dialog"
    >
      <div class="unlock-result">
        <div class="result-animation">
          <img 
            :src="unlockResult.success ? 'https://cdn-icons-png.flaticon.com/512/4341/4341069.png' : 'https://cdn-icons-png.flaticon.com/512/6711/6711656.png'" 
            :alt="unlockResult.success ? 'NFT' : '失败'" 
            class="result-image"
          >
        </div>
        <div class="result-info">
          <h3>{{ unlockResult.message }}</h3>
          <template v-if="unlockResult.success">
            <div class="nft-info">
              <div class="nft-item">
                <span class="nft-label">名称：</span>
                <span class="nft-value">{{ unlockResult.nft?.name }}</span>
              </div>
              <div class="nft-item">
                <span class="nft-label">魅力值：</span>
                <span class="nft-value">{{ unlockResult.nft?.charm }}</span>
              </div>
              <div class="nft-item">
                <span class="nft-label">稀有度：</span>
                <span class="nft-value" :style="{ color: getRarityColor(unlockResult.nft?.rarity) }">
                  {{ unlockResult.nft?.rarity }}
                </span>
              </div>
            </div>
            <div v-if="unlockResult.txHash" class="mint-info">
              <div class="mint-status">NFT 铸造成功！</div>
              <el-link 
                type="primary" 
                :href="'https://sepolia.etherscan.io/tx/' + unlockResult.txHash" 
                target="_blank"
                class="tx-link"
              >
                在区块链浏览器中查看 <el-icon><Link /></el-icon>
              </el-link>
            </div>
          </template>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="unlockResult.visible = false">关闭</el-button>
          <el-button 
            v-if="canExplore"
            type="primary" 
            @click="continueExploration"
          >
            继续探索
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加能量弹窗 -->
    <el-dialog
      v-model="energyDialog.visible"
      title="添加能量"
      width="400px"
      center
      class="energy-dialog"
    >
      <div class="energy-add">
        <el-input-number 
          v-model="energyDialog.amount" 
          :min="1" 
          :max="100"
          size="large"
          controls-position="right"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button plain @click="energyDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddEnergy">确认添加</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';
import { useWalletStore } from '../stores/walletStore';
import { Star, Search, Link, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { generateAvatar } from '../interact/Asistant';
import { ethers } from 'ethers';

const walletStore = useWalletStore();
const isExploring = ref(false);
const logContent = ref(null);

// 玩家信息
const playerInfo = ref({
  energy: 0,
  avatar: generateAvatar(walletStore.walletAddress)
});
onMounted(async () => {
  playerInfo.value.energy = await walletStore.tokenContract.balanceOf(walletStore.walletAddress);
  // 批准代币
  const approveTx = await walletStore.tokenContract.approve(walletStore.contract.address, 5000);
  console.log("批准代币交易已发送，交易哈希为：", approveTx.hash);
});
// 探索日志
const explorationLogs = ref([]);

// 宝箱弹窗
const treasureDialog = ref({
  visible: false,
  question: '',
  answer: '',
  unlocking: false,
  treasure: null
});

// 解锁结果
const unlockResult = ref({
  visible: false,
  success: false,
  message: '',
  nft: null,
  txHash: ''
});

// 能量添加弹窗
const energyDialog = ref({
  visible: false,
  amount: 10
});

// 是否可以探索
const canExplore = computed(() => {
  return playerInfo.value.energy >= 10 && walletStore.isConnected;
});

// 格式化地址显示
const formatAddress = (address) => {
  if (!address) return '未连接钱包';
  return address.slice(0, 6) + '...' + address.slice(-4);
};

// 格式化时间
const formatTime = (date) => {
  return new Date(date).toLocaleTimeString('zh-CN', { hour12: false });
};

// 获取稀有度颜色
const getRarityColor = (rarity) => {
  switch (rarity) {
    case '传说': return '#FFD700';
    case '史诗': return '#9932CC';
    case '稀有': return '#0066CC';
    case '罕见': return '#32CD32';
    default: return '#808080';
  }
};

// 添加日志
const addLog = (log) => {
  explorationLogs.value.unshift(log);
  if (explorationLogs.value.length > 50) {
    explorationLogs.value.pop();
  }
  nextTick(() => {
    if (logContent.value) {
      logContent.value.scrollTop = 0;
    }
  });
};

// 清空日志
const clearLog = () => {
  explorationLogs.value = [];
};
let probability = 0.5; // 50%的概率找到宝箱
// 开始探索
const startExploration = async () => {

  if (playerInfo.value.energy < 10) {
    ElMessage.warning('能量不足，需要至少10点能量进行探索');
    return;
  }

  isExploring.value = true;
  addLog({
    type: 'info',
    message: `目前余额为${playerInfo.value.energy}，花费10代币，开始探索...`,
    time: new Date()
  });


  try {
    // 扣除能量
    playerInfo.value.energy -= 10;
    
    // 调用智能合约扣除能量
    const tx = await walletStore.contract.deductTokens(walletStore.walletAddress, 10);
    
    // 模拟探索过程
    const found = Math.random() > probability // 30%的概率发现宝箱
    console.log('挖到宝藏概率:', 1-probability);
    if (found) {
      const treasure = await generateTreasure();
      treasureDialog.value = {
        visible: true,
        question: treasure.question,
        answer: '',
        unlocking: false,
        treasure
      };
      
      addLog({
        type: 'success',
        message: '发现了一个神秘宝箱！',
        time: new Date()
      });
    } else {
      probability -= 0.01
      addLog({
        type: 'warning',
        message: '这次什么都没找到...',
        time: new Date()
      });
    }
  } catch (error) {
    console.error('探索过程出错：', error);
    ElMessage.error('探索失败：' + error.message);
    addLog({
      type: 'error',
      message: '探索失败：' + error.message,
      time: new Date()
    });
  } finally {
    isExploring.value = false;
  }
};

// 生成宝藏
const generateTreasure = async () => {
  try {
    // 调用智能合约生成宝藏
    const tx = await walletStore.contract.mint(walletStore.walletAddress);
    const receipt = await tx.wait();
    
    // 从事件中获取 tokenId
    const event = receipt.events.find(event => event.event === 'Transfer');
    const tokenId = event.args[2]; // Transfer 事件的第三个参数是 tokenId
    
    console.log('铸造的 NFT tokenId:', tokenId.toString());

    // 获取 NFT 元数据
    const uri = await walletStore.contract.tokenURI(tokenId);
    console.log('NFT URI:', uri);
    
    const response = await fetch(uri);
    const metadata = await response.json();
    console.log('NFT 元数据:', metadata);
    console.log('NFT 问题:', metadata.attributes[2].value);
    const answerHash = "0x"+metadata.answer_hash
    const charm = metadata.attributes[1].value
    // 调用智能合约设置答案
    try{
        walletStore.contract.setAnswer(tokenId, answerHash, charm)
        console.log('设置答案成功:', answerHash)
    }catch(error){
        console.error('设置答案失败:', error);
    }
    const rarity = metadata.attributes[0].value
    return {
      id: tokenId.toString(),
      name: `数字宝藏 #${rarity} ${tokenId}`,
      rarity: rarity,
      charm: charm,
      question: metadata.attributes[2].value + "= ？", // 假设问题存储在 attributes[1] 中
      image: metadata.image || 'https://cdn-icons-png.flaticon.com/512/2535/2535557.png'
    };
  } catch (error) {
    console.error('生成宝藏失败:', error);
    playerInfo.value.energy += 10;
    throw error;
  }
};

// 调用智能合约验证答案
const validateAnswer = async (answer, tokenId) => {
  try {
    // 确保使用正确的钱包发送交易
    
    const isCorrect = await walletStore.contract.solvePuzzle(answer, tokenId);
    return isCorrect;
  } catch (error) {
    // 提取合约 revert 的错误信息
    let errorMessage = '验证答案失败';
    if (error.reason) {
      errorMessage = error.reason;
    } else if (error.data?.message) {
      errorMessage = error.data.message;
    } else if (typeof error === 'object' && error.message) {
      // 使用正则表达式提取引号中的错误信息
      const match = error.message.match(/reverted with reason string '([^']+)'/);
      if (match && match[1]) {
        errorMessage = match[1];
      }
    }
    console.error('验证答案失败:', errorMessage);
    throw new Error(errorMessage);
  }
};

// 跳过宝箱
const skipTreasure = () => {
  treasureDialog.value.visible = false;
  addLog({
    type: 'warning',
    message: '宝箱已存入背包，稍后解锁宝箱...',
    time: new Date()
  });
};

// 解锁宝箱
const unlockTreasure = async () => {
  if (!treasureDialog.value.answer) {
    ElMessage.warning('请输入答案');
    return;
  }

  treasureDialog.value.unlocking = true;

  try {
    const isCorrect = await validateAnswer(treasureDialog.value.answer, treasureDialog.value.treasure.id);
    
    if (isCorrect) {
      unlockResult.value = {
        visible: true,
        success: true,
        message: '恭喜你成功解锁宝箱！',
        nft: treasureDialog.value.treasure,
        txHash: 'asdasdas'
      };

      addLog({
        type: 'success',
        message: '成功解锁宝箱并获得了奖励！',
        time: new Date()
      });
      
      // 成功时关闭宝箱对话框
      treasureDialog.value.visible = false;
    }
  } catch (error) {
    console.error('解锁宝箱出错：', error);
    
    // 根据错误类型设置不同的提示信息
    let message = '解锁失败';
    if (error.message.includes('answer is wrong')) {
      message = '答案错误，请重试';
      // 答案错误时，清空输入框让用户重新输入
      treasureDialog.value.answer = '';
      ElMessage.error(message);
      treasureDialog.value.unlocking = false;
      return; // 直接返回，不关闭对话框
    } else if (error.message.includes('has been opened')) {
      message = '这个宝箱已经被打开过了';
    } else if (error.message.includes('not the owner')) {
      message = '你不是这个宝藏的所有者';
    } else if (error.message.includes('enough reward')) {
      message = '合约中的奖励代币不足';
    }
    
    unlockResult.value = {
      visible: true,
      success: false,
      message: message,
      nft: null,
      txHash: ''
    };

    addLog({
      type: 'error',
      message: `解锁宝箱失败：${message}`,
      time: new Date()
    });
    
    ElMessage.error(message);
    // 其他错误时关闭宝箱对话框
    treasureDialog.value.visible = false;
  } finally {
    treasureDialog.value.unlocking = false;
  }
};

// 继续探索
const continueExploration = () => {
  unlockResult.value.visible = false;
  if (canExplore.value) {
    startExploration();
  }
};

// 添加能量
const addEnergy = () => {
  energyDialog.value.visible = true;
};

// 确认添加能量
const confirmAddEnergy = async() => {
  const amount = energyDialog.value.amount;
  const tx = await walletStore.contract.addTokens(walletStore.walletAddress,amount);
  playerInfo.value.energy = Math.min(100, playerInfo.value.energy + amount);
  energyDialog.value.visible = false;
  probability -= 0.1;
  probability = probability < 0 ? 0.5: probability;
  addLog({
    type: 'info',
    message: `添加了 ${amount} 点能量`,
    time: new Date()
  });
  
  ElMessage.success(`成功添加 ${amount} 点能量`);
};
</script>
<style scoped>
.game-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.status-section {
  position: relative;
  z-index: 1;
}

.player-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.player-info {
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 30px;
}

.player-avatar {
  text-align: center;
}

.player-address {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.energy-info {
  flex: 1;
}

.energy-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  color: #409EFF;
  font-weight: bold;
}

.add-energy-btn {
  margin-left: auto;
}

.energy-bar {
  margin-top: 5px;
}

.main-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.explore-section {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  border-radius: 12px;
  overflow: hidden;
}

.explore-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
  opacity: 0.1;
}

.explore-content {
  position: relative;
  text-align: center;
  padding: 40px;
}

.explore-title {
  margin-bottom: 40px;
}

.explore-title h1 {
  font-size: 2.5em;
  margin-bottom: 10px;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.explore-title p {
  color: #666;
  font-size: 1.1em;
}

.explore-button {
  padding: 20px 50px;
  font-size: 1.2em;
}

.energy-cost {
  margin-top: 15px;
  color: #f56c6c;
}

.log-section {
  height: 400px;
}

.log-card {
  height: 100%;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-content {
  height: calc(100% - 60px);
  overflow-y: auto;
  padding: 10px;
}

.log-item {
  padding: 8px;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.log-item:hover {
  background: rgba(0, 0, 0, 0.02);
}

.log-time {
  color: #909399;
  font-size: 0.9em;
  margin-right: 10px;
}

.log-success {
  color: #67c23a;
}

.log-warning {
  color: #e6a23c;
}

.log-error {
  color: #f56c6c;
}

.log-info {
  color: #909399;
}

.treasure-dialog :deep(.el-dialog__header),
.result-dialog :deep(.el-dialog__header) {
  padding: 20px;
  margin-right: 0;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f);
  color: white;
}

.treasure-dialog :deep(.el-dialog__title),
.result-dialog :deep(.el-dialog__title) {
  color: white;
}

.treasure-result,
.unlock-result {
  padding: 20px;
  text-align: center;
}

.treasure-animation,
.result-animation {
  margin-bottom: 20px;
}

.treasure-image1,
.result-image {
  width: 200px;
  height: 200px;
  object-fit: cover;
  animation: float 3s ease-in-out infinite;
}

.treasure-info,
.result-info {
  text-align: center;
}

.treasure-info h3,
.result-info h3 {
  margin-bottom: 20px;
  color: #303133;
}

.treasure-question {
  margin-top: 30px;
}

.question-text {
  font-size: 1.2em;
  margin-bottom: 15px;
  color: #409EFF;
}

.answer-input {
  width: 200px;
  margin: 0 auto;
}

.nft-info {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.nft-item {
  margin: 10px 0;
}

.nft-label {
  color: #909399;
  margin-right: 10px;
}

.nft-value {
  font-weight: bold;
}

.mint-info {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.mint-status {
  color: #67c23a;
  font-weight: bold;
  margin-bottom: 10px;
}

.tx-link {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.energy-add {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding-top: 20px;
}

@keyframes float {
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
}

/* 响应式布局 */
@media (max-width: 768px) {
  .main-section {
    grid-template-columns: 1fr;
  }

  .player-info {
    flex-direction: column;
    text-align: center;
  }

  .energy-info {
    width: 100%;
  }

  .explore-title h1 {
    font-size: 2em;
  }
}
</style>

